import Foundation
import SwiftUI

class TimeManager: ObservableObject {
    @Published var remainingTime: TimeInterval = 30 * 60
    @Published var currentPosture: PostureType = .sitting
    @Published var isPaused: Bool = true
    @Published var overtimeMinutes: Int = 0
    
    var timer: Timer?
    private var overtimeTimer: Timer?
    private var standingDuration: Double
    private var sittingDuration: Double
    private var isScreenLocked = false
    
    init(standingDuration: Double = 30, sittingDuration: Double = 30) {
        self.standingDuration = standingDuration
        self.sittingDuration = sittingDuration
        resetTimer()
        
        // 监听锁屏和解锁事件
        NSWorkspace.shared.notificationCenter.addObserver(
            self,
            selector: #selector(screenDidLock),
            name: NSWorkspace.screensDidSleepNotification,
            object: nil
        )
        
        NSWorkspace.shared.notificationCenter.addObserver(
            self,
            selector: #selector(screenDidUnlock),
            name: NSWorkspace.screensDidWakeNotification,
            object: nil
        )
    }
    
    @objc private func screenDidLock() {
        isScreenLocked = true
    }
    
    @objc private func screenDidUnlock() {
        isScreenLocked = false
        // 解锁时不需要做其他操作
    }
    
    func updateDurations(standing: Double, sitting: Double) {
        self.standingDuration = standing
        self.sittingDuration = sitting
        resetTimer()
    }
    
    func startTimer() {
        stopOvertimeTimer()
        
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
            guard let self = self else { return }
            
            if self.remainingTime > 0 {
                self.remainingTime -= 1
                let currentDuration = self.currentPosture == .standing ? self.standingDuration : self.sittingDuration
                let progress = self.remainingTime / (currentDuration * 60)
                DockTileManager.shared.updateProgress(progress, posture: self.currentPosture)
            } else {
                self.stopTimer()
                self.startOvertimeTimer()
                // 只在非锁屏状态发送通知
                if !self.isScreenLocked {
                    NotificationManager.shared.sendNotification(for: self.currentPosture, overtimeMinutes: self.overtimeMinutes)
                }
            }
        }
        isPaused = false
    }
    
    private func startOvertimeTimer() {
        overtimeMinutes = 0
        overtimeTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
            guard let self = self else { return }
            self.overtimeMinutes += 1
            // 只在非锁屏状态发送通知
            if !self.isScreenLocked {
                NotificationManager.shared.sendNotification(for: self.currentPosture, overtimeMinutes: self.overtimeMinutes)
            }
        }
    }
    
    private func stopOvertimeTimer() {
        overtimeTimer?.invalidate()
        overtimeTimer = nil
        overtimeMinutes = 0
    }
    
    func stopTimer() {
        timer?.invalidate()
        timer = nil
        isPaused = true
    }
    
    func switchPosture() {
        stopTimer()
        stopOvertimeTimer()
        // 移除已显示的系统通知
        NotificationManager.shared.removeLastNotification()
        currentPosture = currentPosture.nextPosture
        resetTimer()
        DockTileManager.shared.updateProgress(1.0, posture: currentPosture)
        startTimer()
    }
    
    func resetTimer() {
        stopOvertimeTimer()
        let duration = currentPosture == .standing ? standingDuration : sittingDuration
        remainingTime = duration * 60
    }
    
    func toggleTimer() {
        if timer == nil {
            startTimer()
        } else {
            stopTimer()
        }
    }
    
    func timeString() -> String {
        let minutes = Int(remainingTime) / 60
        let seconds = Int(remainingTime) % 60
        return String(format: "%02d:%02d", minutes, seconds)
    }
}
